// @ts-nocheck


var express = require('express');

const { rmSync } = require('fs');

var axios = require("axios")

var router = express.Router();

const multer = require('multer'); 

require('../db/connect');

const {FindOneData,FindManyData,InsertManyData,UpdateManyData,RemoveData} = require('../db/index');

const {getToken,checkToken} = require('../utils/token');

const {shopper_model,level_model,product_model,pcate_model,ptype_model,announce_model,annoType_model,message_model, grade_model} = require('../db/model');


// 测试接口
router.get('/test',(req,res)=>{
    res.json({
        code:200,
        data:"",
        msg:"接口测试成功！"
    });
});

// 用户注册
router.post('/register',(req,res)=>{
    let body = req.body ; 
    body.time = new Date() ; 
    FindOneData({
        model:shopper_model,
        query:{
            $or:[
                {
                    username:body.username
                },
                {
                    phone:body.phone
                }
            ]
        },
        res,
        callback(result){
            if(result){
                res.json({
                    code:401,
                    msg:'用户已存在，请重新注册',
                    data:result,
                });
            } else {
                InsertManyData({
                    model:shopper_model,
                    data:body,
                    res,
                    msg:'注册成功！'
                });
            }
        }
    });
});

// 用户名登录
router.post('/byName',(req,res)=>{
    let body = req.body ; 
    FindOneData({
        model:shopper_model,
        query:body,
        res,
        callback(result){
            if(result){
                let token = getToken(body);
                res.json({
                    code:200,
                    msg:'登录成功！',
                    data:result,
                    token
                });
            } else {
                res.json({
                    code:401,
                    msg:'登录失败，用户名或密码错误!',
                    data:result
                });
            }
        }
    });
});


// 发送验证码 
router.post("/sendCaptcha",(req,res)=>{
    var body = req.body;
    // 先去查询一下 
    // 再去发送验证码 
    FindOneData({
        model:shopper_model,
        query:body,
        res,
        callback(result){
            if(result){
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/sent",{
                    params:body // {phone:xxxxxx}
                })
                .then(({data})=>{
                    console.log(data)
                    if(data.code==200){
                        res.json({
                            code:200,
                            data,
                            msg:'验证码发送成功'
                        })
                    }else{
                        res.json({
                            code:401,
                            data,
                            msg:'验证码发送失败'
                        })
                    }
                    
                })
            }else{
                res.json({
                    code:401,
                    msg:'手机号未注册,请先注册',
                    result 
                })
            }
        }
    })
})


// 验证验证码
router.post("/checkCaptcha",(req,res)=>{
    var body = req.body;  // phone captcha
    FindOneData({
        model:shopper_model,
        query:{ phone: body.phone },
        res,
        callback(result){
            if(result){
                // 发送验证code 
                axios.get("http://47.104.209.44:3333/captcha/verify",{
                    params:body // {phone:xxxxxx}
                })
                .then(({data})=>{
                    // console.log(data);
                    // data.code==200
                    if(data.code==200){
                        var token = getToken({
                            username:result.username,
                            password:result.password,
                            phone:result.phone 
                        })
                        res.json({
                            code:200,
                            data:result,
                            msg:'验证码校验成功',
                            token
                        })
                    }else{
                        res.json({
                            code:401,
                            data,
                            msg:'验证码校验失败'
                        })
                    }
                })
            }else{
                res.json({
                    code:401,
                    msg:'手机号未注册,请先注册',
                    result 
                })
            }
        }
    })
})

// 获取用户信息
router.post("/getUserInfo",(req,res)=>{
    checkToken(req,res,({username})=>{
        FindOneData({
            model:shopper_model,
            query:{username},
            msg:'获取个人信息成功！',
            res
        });
    });
});

// 定义文件上传的目录
const storage = multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'./public/images/uploads');
    },
    filename:function(req,file,cb){
        const uniqueSuffix = 'manage_'+Date.now()+'_'+Math.round(Math.random() * 1E9) ; 
        cb(null,file.fieldname+'_'+uniqueSuffix+file.originalname);
    }
});

const upload = multer({storage:storage}).any();
// 文件上传接口
router.post('/uploads',upload,(req,res)=>{
    let path = req.files[0].path ; 
    res.json({
        code:200,
        msg:'上传成功！',
        path,
        data:path
    });
});

// 修改密码
router.post('/changeUPass',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        FindOneData({
            model:shopper_model,
            query:{username,password:body.oldpass},
            res,
            callback(result){
                if(result){
                    UpdateManyData({
                        model:shopper_model,
                        query:result,
                        data:{password:body.newpass},
                        res,
                        msg:"修改成功！"
                    });
                } else {
                    res.json({
                        code:401,
                        data:null,
                        msg:"用户名或密码错误"
                    });
                }
            }
        });
    });
});

// 用户修改信息
router.post('/changeUserInfo',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:shopper_model,
            query:{username},
            data:body,
            res,
            msg:'成功！'
        });
    });
});

// 添加角色
router.post('/roleAdd',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:level_model,
            data:body,
            res,
            msg:'角色新增成功！'
        });
    });
});
// 修改角色信息和属性
router.post('/roleUpd',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:level_model,
            query:{_id:req.body._id},
            data:body,
            res,
            msg:'角色属性修改成功！'
        });
    });
});

// 查询角色属性列表
router.post('/getRoleList',(req,res)=>{
    let body = req.body ; 
    let query = {} ; 
    checkToken(req,res,({username})=>{
        FindManyData({
            model:level_model,
            query:query,
            res,
            msg:'获取角色信息成功!'
        });
    });
});

// 用户修改
router.post('/updUser',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:shopper_model,
            query:{_id:req.body._id},
            data:body,
            res,
            msg:'用户信息修改成功！'
        });
    });
});
// 用户新增
router.post('/addUser',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:shopper_model,
            data:body,
            res,
            msg:'添加用户完成！'
        });
    });
});

// 用户列表   所有用户

router.post('/getUserList',(req,res)=>{
    let body = req.body ; 
    let query = {} ; 
    switch(true){
        case body.keyword:
            query = {...query,username:new RegExp(keyword)}
        case body.role:
            query = {...query,role:body.role}
        default:
            break;
    }

    checkToken(req,res,({username})=>{
        FindManyData({
            model:shopper_model,
            data:query,
            res,
            msg:'获取用户信息列表完成！'
        });
    });
});
// 商品新增
router.post('/addGoods',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:product_model,
            data:body,
            res,
            msg:'商品添加成功！'
        });
    });
});
// 商品修改
router.post('/updGoods',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:product_model,
            query:{_id:body._id},
            data:body,
            res,
            msg:'商品信息修改完成！'
        });
    });
});

// 商品删除
router.post('/delGoods',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        RemoveData({
            model:product_model,
            query:{_id:body._id},
            res,
            msg:'商品已被删除！'
        });
    });
});


// 商品列表包含查询功能
// to  do   
// cateid   typeid    percent    price     
// 
router.post('/getGoodsList',(req,res)=>{
    let body = req.body ;
    // {cateid,typeid,percent,price,keyword} 
    let query = {} ; 
    switch(true){
        case body._id:
            query = {...query,_id:body._id}
        case body.cateid:
            query = {...query,cateid:body.cateid};
        case body.typeid:
            query = {...query,typeid:body.typeid};
        case body.percent:
            query = {...query,percent:body.percent};
        case body.keyword:
            query = {...query,$or:[
                {
                    name:new RegExp(body.keyword)
                },
                {
                    details:new RegExp(body.keyword)
                }
            ]};
        default:
            break ; 
    }
    checkToken(req,res,({username})=>{
        FindManyData({
            model:product_model,
            query:query,
            res,
            msg:'获取商品列表成功！'
        });
    });
});

// 商品类型新增
router.post('/addCate',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:pcate_model,
            data:body,
            res,
            msg:'商品类型添加完成！'
        });
    });
});
// 商品类型修改
router.post('/updCate',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:pcate_model,
            query:{_id:body._id},
            data:body,
            res,
            msg:'商品类型修改成功！'
        });
    });
});


// 商品类型查询
// keyword
router.post('/getCateList',(req,res)=>{
    let body = req.body ;
    let query = {} ;  
    if(body.keyword){
        query = {
            $or:[
                {
                    ptypename:new RegExp(body.keyword),
                },
                {
                    subTypename:new RegExp(body.keyword),
                }
            ]
        }
    }
    checkToken(req,res,({username})=>{
        FindManyData({
            model:pcate_model,
            query:query,
            res,
            msg:'获取商品类型列表成功！'
        });
    });
});
// 新增通知
router.post('/addAnnounce',(req,res)=>{
    let body = req.body ;
    checkToken(req,res,({username})=>{
        FindManyData({
            model:announce_model,
            data:body,
            res,
            msg:'添加通知完成！'
        });
    });
});
// 修改通知
router.post('/updAnnounce',(req,res)=>{
    let body = req.body ;
    checkToken(req,res,({username})=>{
        FindManyData({
            model:announce_model,
            query:{_id:body._id},
            data:body,
            res,
            msg:'修改成功！'
        });
    });
});
// 查询通知
// 
// keyword      annoTypeid
// 
router.post('/getAnnoList',(req,res)=>{
    let body = req.body ;
    let query = {};
    switch(true){
        case body.annoTypeid:
            query = {...query,annoTypeid:body.annoTypeid};
        case body.keyword:
            query = {...query,$or:[
                {
                    annoTitle:new RegExp(body.keyword)
                },
                {
                    annoContent:new RegExp(body.keyword)
                }
            ]};
        default:
            break ; 
    }
    checkToken(req,res,({username})=>{
        FindManyData({
            model:announce_model,
            query:query,
            res,
            msg:'获取通知完成！'
        });
    });
});
// 新增类别   包括子类
router.post('/addType',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:ptype_model,
            data:body,
            res,
            msg:'添加成功！'
        });
    });
});
// 修改类别   包括子类
router.post('/updType',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:ptype_model,
            query:{_id:body._id},
            data:body,
            res,
            msg:'修改成功！'
        });
    });
});



// 查询类别   包括子类

// keyword  
router.post('/getTypeList',(req,res)=>{
    let body = req.body ; 
    let query = {} ;
    if(body.keyword){
        query = {
            $or:[
                {
                    ptypename:new RegExp(body.keyword)
                },
                {
                    subTypename:new RegExp(body.keyword)
                }
            ]
        }
    }
    checkToken(req,res,({username})=>{
        FindManyData({
            model:ptype_model,
            query:query,
            res,
            msg:'获取商品类别信息完成！'
        });
    });
});


// 添加留言   

router.post('/addMessage',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        InsertManyData({
            model:message_model,
            data:body ,
            res,
            msg:'添加留言完成！'
        });
    });
});


// 查询发送的留言

router.post('/getSendMsgList',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        FindManyData({
            model:message_model,
            query:{sendid:body.sendid},
            res,
            msg:'获取信息成功！'
        });
    });
});


//查询回复的留言

router.post('/getRceMsgList',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        FindManyData({
            model:message_model,
            query:{receiveid:body.receiveid},
            res,
            msg:'获取信息成功！'
        });
    });
});


// 修改留言状态    is_read  false  未读   true  已读
router.post('/updMsg',(req,res)=>{
    let body = req.body ; 
    checkToken(req,res,({username})=>{
        UpdateManyData({
            model:message_model,
            query:{_id:body._id},
            data:body,
            res,
            msg:'获取信息成功！'
        });
    });
});

// // 学员成绩添加
// router.post('/addGrade',(req,res)=>{
//     let body = req.body ; 
//     body.time = new Date();
//     checkToken(req,res,({username})=>{
//         InsertManyData({
//             model:grade_model,
//             data:body,
//             res,
//             msg:'学员成绩添加成功！'
//         });
//     });
// });

// // 学员成绩修改
// router.post('/updGrade',(req,res)=>{
//     let body = req.body ; 
//     checkToken(req,res,({username})=>{
//         UpdateManyData({
//             model:grade_model,
//             query:{_id:body._id},
//             data:body,
//             res,
//             msg:'学员成绩修改成功！'
//         });
//     });
// });

// // 学员成绩删除
// router.post('/updGrade',(req,res)=>{
//     let body = req.body ; 
//     checkToken(req,res,({username})=>{
//         RemoveData({
//             model:grade_model,
//             query:{_id:body._id},
//             res,
//             msg:'学员成绩删除成功！'
//         });
//     });
// });


// // 学员成绩查询
// router.post('/updGrade',(req,res)=>{
//     let body = req.body ; 
//     let query = {} ; 
//     switch(true){
//         case body.stuLevel:
//             query = {...query,stuLevel:body.stuLevel} ; 
//         case body.stuGlory:
//             query = {...query,stuGlory:body.stuGlory} ; 
//         case body.keyword:
//             query = {
//                 ...query,
//                 $or:[
//                     {stuName:new RegExp(body.keyword)},
//                     {remark:new RegExp(body.keyword)}
//                 ]
//             }
//         default:
//             break;
//     }
//     checkToken(req,res,({username})=>{
//         RemoveData({
//             model:grade_model,
//             query:query,
//             res,
//             msg:'学员成绩删除成功！'
//         });
//     });
// });

module.exports = router;